package com.xxxx.yebserver.common.utils;

import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component("jwtTokenUtils")
public class JwtTokenUtils {
    private long tokenExpiration = 24*60*60*1000;
    private String tokenSignKey = "cxq_abc";



    /**
     * 生成token字符串
     * @param username
     * @return
     */
    public String createToken(String username) {
        return Jwts.builder().setSubject(username)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .setExpiration(new Date(System.currentTimeMillis()+tokenExpiration))
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    /**
     * 通过token字符串解析出用户名
     * @param token
     * @return
     */
    public String getUserFromToken(String token) {
        return Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody().getSubject();
    }

    /**
     * 验证token是否过期
     * @param token
     * @return
     */
    public Boolean validateToken(String token){
        Date exp = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody().getExpiration();
        long time = exp.getTime();
        long now = System.currentTimeMillis();
        return now < time;
    }

}
